#!/bin/bash

# 修复现有容器的脚本

echo "=== 修复现有Docker容器 ==="

# 停止容器
echo "停止容器..."
docker stop unitechoose8

# 创建启动脚本并复制到容器中
echo "创建启动脚本..."
cat > temp-start.sh << 'EOF'
#!/bin/bash
set -e

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 错误处理函数
handle_error() {
    log "ERROR: $1"
    exit 1
}

# 检查数据库目录
if [ ! -d "/app/data" ]; then
    log "Creating data directory..."
    mkdir -p /app/data
fi

# 检查是否需要启动开发模式
if [ "$DEV_MODE" = "true" ]; then
    log "Starting in development mode..."
    if command -v node >/dev/null 2>&1; then
        log "Starting frontend development server..."
        cd /app/frontend || handle_error "Failed to change to frontend directory"
        npm run dev &
        FRONTEND_PID=$!
        cd /app || handle_error "Failed to change back to app directory"
        
        log "Starting backend server..."
        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload &
        BACKEND_PID=$!
        
        wait $FRONTEND_PID $BACKEND_PID
    else
        log "Node.js not found, starting backend only..."
        python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload
    fi
else
    log "Starting in production mode..."
    if [ ! -d "/app/backend" ]; then
        handle_error "Backend directory not found"
    fi
    
    log "Starting production server..."
    python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --workers 1
fi
EOF

# 复制启动脚本到容器
echo "复制启动脚本到容器..."
docker cp temp-start.sh unitechoose8:/app/start.sh

# 设置执行权限
echo "设置执行权限..."
docker exec unitechoose8 chmod +x /app/start.sh

# 删除临时文件
rm temp-start.sh

# 重启容器
echo "重启容器..."
docker start unitechoose8

echo "✅ 容器修复完成"
echo "查看容器日志："
docker logs -f unitechoose8
